package cn.hy.pms.thrift.utils;

import cn.hy.pms.thrift.*;
import cn.hy.preparelesson.common.entity.*;
import cn.hy.preparelesson.common.exception.MessageException;
import cn.hy.preparelesson.common.vo.StafffVo;
import cn.hy.preparelesson.common.vo.SysUserIdAndNameVo;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.wealoha.thrift.PoolConfig;
import com.wealoha.thrift.ServiceInfo;
import com.wealoha.thrift.ThriftClient;
import com.wealoha.thrift.ThriftClientPool;
import org.apache.commons.lang3.StringUtils;
import org.apache.thrift.TApplicationException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * thrift客户端工具类，使用连接池
 */
public class ThriftUtils {
    public static ThriftClientPool<PmsThriftService.Client> pool;

    public static void init(String thriftHost, Integer thriftPort) {
        PoolConfig config = new PoolConfig();
        config.setMinIdle(2);
        config.setMaxTotal(20);
        pool = new ThriftClientPool<>(Collections.singletonList(new ServiceInfo(thriftHost, thriftPort)), e -> new PmsThriftService.Client(new TBinaryProtocol(e)), config);
    }

    /**
     * 根据用户id集合查询用户信息
     * @param userIds
     * @return
     */
    public static List<SysUserThrift> findUserByUserIdList(List<String> userIds) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            List<SysUserThrift> sutList = pmsThriftService.findUserByUserIdList(userIds);
            client.finish();
            return sutList;
        } catch (TException e) {
            return handleThriftException(e);
        }
    }

    /**
     * 根据用户id查询用户信息
     * @param userId
     * @return
     */
    public static SysUserThrift findUserByUserId(String userId) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            SysUserThrift sut = pmsThriftService.findUserByUserId(userId);
            client.finish();
            return sut;
        } catch (TException e) {
            return handleThriftException(e);
        }
    }

    private static <T>T handleThriftException(TException e) throws TException {
        if (e instanceof TApplicationException && ((TApplicationException) e).getType() == TApplicationException.MISSING_RESULT) {
            return null;
        } else if (e instanceof ThriftBusinessException) {
            throw new MessageException(((ThriftBusinessException) e).message);
        }  else {
            throw new TException(e);
        }
    }

    /**
     * 根据用户id，应用编码查询用户在那些学校有这些应用
     * @param userId
     * @return
     */
    public static List<SchoolRoleVoThrift> findSchoolByUserIdAndAppCode(String userId, String appCode) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            List<SchoolRoleVoThrift> srvList = pmsThriftService.findSchoolByUserIdAndAppCode(userId, appCode);
            client.finish();
            return srvList;
        } catch (TException e) {
            return handleThriftException(e);
        }
    }


    /**
     * 根据学校id, LIKE用户真实姓名 查询用户信息
     * @param
     * @return
     */
    public static List<SysUserThrift> findUserBySchoolIdAndRealNameLike(String schoolId, String realName) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            List<SysUserThrift> sutList = pmsThriftService.findUserBySchoolIdAndRealNameLike(schoolId, realName);
            client.finish();
            return sutList;
        } catch (TException e) {
            return handleThriftException(e);
        }
    }

    /**
     * 根据schoolId查询树型机构信息
     * @param
     * @return
     */
    public static List<SysOfficeThrift> findTreeOfficeBySchooId(String schoolId) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            List<SysOfficeThrift> sotList = pmsThriftService.findTreeOfficeBySchoolId(schoolId);
            client.finish();
            return sotList;
        } catch (TException e) {
            return handleThriftException(e);
        }
    }


    /**
     * 根据学校id和其他参数（机构id）(后期动态补充)查询所有用户id信息
     * @param schoolId
     * @param officeId
     * @return
     * @throws TException
     */
    public static List<String> findUserIdBySchoolIdAndOtherParams(String schoolId, String officeId) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            List<String> userIdList = pmsThriftService.findUserIdBySchoolIdAndOtherParams(schoolId, officeId);
            client.finish();
            return userIdList;
        } catch (TException e) {
            return handleThriftException(e);
        }
    }

    /**
     * 查询用户Id集合信息，使用json字符串参数
     * @param schoolId
     * @param jsonParams
     * @return
     * @throws TException
     */
    public static List<String> findUserIdListWithJsonParams(String schoolId, String jsonParams) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            String userIdListStr = pmsThriftService.findUserIdListWithJsonParams(schoolId, jsonParams);
            client.finish();
            return JSONObject.parseArray(userIdListStr, String.class);
        } catch (TException e) {
            return handleThriftException(e);
        }
    }


    /**
     * 根据userId、schoolId、appCode查询userId用户在schoolId学校、appCode应用下的权限信息
     * @param userId
     * @return
     */
    public static List<SysMenuPermissionThrift> findMenuPermByUserIdAndSchoolIdAndAppCode(String userId, String schoolId, String appCode) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            List<SysMenuPermissionThrift> smpList = pmsThriftService.findMenuPermByUserIdAndSchoolIdAndAppCode(userId, schoolId, appCode);
            client.finish();
            return smpList;
        } catch (TException e) {
            return handleThriftException(e);
        }
    }

    /**
     * 根据schoolId,officeType 查询机构树状集合
     * @param schoolId
     * @param officeType
     * @return
     * @throws TException
     */
    public static List<SysOfficeThrift> findTreeOfficeBySchoolIdAndOfficeType(String schoolId, Byte officeType) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            List<SysOfficeThrift> sotList = pmsThriftService.findTreeOfficeBySchoolIdAndOfficeType(schoolId, officeType);
            client.finish();
            return sotList;
        } catch (TException e) {
            return handleThriftException(e);
        }
    }

    /**
     * 根据学校id获取年级信息
     * @param schoolId
     * @return
     * @throws TException
     */
    public static  List<BusiGradeOption> findNormalBusiGradeOptionBySchoolId(String schoolId) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            String gradeString = pmsThriftService.findGradeBySchoolId(schoolId);
            if (StringUtils.isBlank(gradeString)) {
                return new ArrayList<>();
            }
            List<BusiGradeOption> gradeList = JSONObject.parseObject(gradeString, new TypeReference<List<BusiGradeOption>>(){});
            client.finish();
            return gradeList;
        } catch (TException e) {
            return handleThriftException(e);
        }
    }

    /**
     * 根据学校id获取科目id
     * @param schoolId
     * @return
     * @throws TException
     */
    public static List<BusiSubject> findSubjectBySchoolId(String schoolId) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            String subjectString = pmsThriftService.findSubjectBySchoolIdAndJsonParams(schoolId, null);
            if (StringUtils.isBlank(subjectString)) {
                return new ArrayList<>();
            }
            List<BusiSubject> subjectList = JSONObject.parseObject(subjectString, new TypeReference<List<BusiSubject>>(){});
            client.finish();
            return subjectList;
        } catch (TException e) {
            return handleThriftException(e);
        }
    }

    /**
     * 根据schoolId,年级获取班级信息
     * @param schoolId
     * @param grade
     * @return
     * @throws TException
     */
    public static List<BusiClass> findSchoolClassByGradeAndSchoolId(String schoolId, String grade, String distanceYear) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            Map<String, String> paramsMap = new HashMap<>(2);
            paramsMap.put("grade", grade);
            paramsMap.put("classDetail", "1");
            paramsMap.put("distanceYear", distanceYear);
            String jsonParams = JSONObject.toJSONString(paramsMap);
            String subjectString = pmsThriftService.findClassBySchoolIdAndJsonParams(schoolId, jsonParams);
            if (StringUtils.isBlank(subjectString)) {
                return new ArrayList<>();
            }
            List<SysOffice> subjectList = JSONObject.parseObject(subjectString, new TypeReference<List<SysOffice>>(){});
            List<BusiClass> collect = subjectList.stream().map(item -> item.getBusiClass()).collect(Collectors.toList());
//            System.out.println(JSONObject.toJSON(collect));
            client.finish();
            return collect;
        } catch (TException e) {
            return handleThriftException(e);
        }
    }

    /**
     * 根据schoolId获取学年学期信息
     * @param schoolId
     * @return
     * @throws TException
     */
    public static List<BusiSchoolSemester> findSemesterBySchoolId(String schoolId) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            String semesterString = pmsThriftService.findSemesterBySchoolId(schoolId);
            if (StringUtils.isBlank(semesterString)) {
                return new ArrayList<>();
            }
            List<BusiSchoolSemester> semesterList = JSONObject.parseObject(semesterString, new TypeReference<List<BusiSchoolSemester>>(){});
            client.finish();
            return semesterList;
        } catch (TException e) {
            return handleThriftException(e);
        }
    }



    //findUserWithOutIdByUserId
    /**
     * 获取全部教职工信息
     * @param schoolId
     * @return
     * @throws TException
     */
    public static List<StafffVo> findStaffListBySchoolId(String schoolId) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            String sysUserStr = pmsThriftService.findStaffBySchoolIdAndJsonParams(schoolId, null);
            if (StringUtils.isBlank(sysUserStr)) {
                return new ArrayList<>();
            }
            List<SysUser> sysUserList = JSONObject.parseObject(sysUserStr, new TypeReference<List<SysUser>>(){});
            List<StafffVo> stafffVoList = new ArrayList<>();
            for (SysUser sysUser : sysUserList) {
                String staffId = sysUser.getId();
                String staffName = StringUtils.isNotBlank(sysUser.getRealName()) ? sysUser.getRealName() : sysUser.getUsername();
                stafffVoList.add(new StafffVo(staffId, staffName));
            }
            client.finish();
            return stafffVoList;
        } catch (TException e) {
            return handleThriftException(e);
        }
    }

    /**
     * 根据用户id集合查询用户信息
     * @param userIds
     * @return
     */
    public static List<SysUserIdAndNameVo> findUserNameByUserIdList(List<String> userIds) throws TException {
        try (ThriftClient<PmsThriftService.Client> client = pool.getClient()) {
            PmsThriftService.Client pmsThriftService = client.iFace();
            List<SysUserIdAndNameVo> resList = new ArrayList<>();
            List<SysUserThrift> sutList = pmsThriftService.findUserByUserIdList(userIds);
            if(CollectionUtils.isEmpty(sutList)) {
                return resList;
            }
            for (SysUserThrift sysUser : sutList) {
                String userId = sysUser.getId();
                String name = StringUtils.isNotBlank(sysUser.getRealName()) ? sysUser.getRealName() : sysUser.getUsername();
                resList.add(new SysUserIdAndNameVo(userId, name));
            }
            client.finish();
            return resList;
        } catch (TException e) {
            return handleThriftException(e);
        }
    }
}
